<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class OperateLogs
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response   =  $next($request);
        // 记录操作日志
        if ($request->attributes->has('user_id')) {
            $method     =  $request->method();
            $path       =  $request->path();
            $ip         =  $request->ip();
            $input      =  json_encode($request->all());
            $output     =  $response->getContent();
            $status     =  $response->getStatusCode();
            $user_id    =  $request->attributes->has('user_id') ? $request->attributes->get('user_id') : 0;
            // 字段长度限制
            if (strlen($input) > 16000) {
                $input = substr($input, 0, 16000);
            }
            if (strlen($output) > 16000) {
                $output = substr($output, 0, 16000);
            }
            try {
                \App\Models\OperateLogs::create([
                    'user_id' => $user_id,
                    'path' => $path,
                    'method' => $method,
                    'ip' => $ip,
                    'input' => $input,
                    'output' => $output,
                    'status' => $status,
                ]);
            } catch (\Exception $e) {
                // 记录日志
                Log::error('操作日志记录失败', ['message' => $e->getMessage()]);
            }
        }

        return $response;
    }
}
